package com.rrd.itext.test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class RequestITextService {
    private String dataFile = "D:\\test3161.xml";
    private String templateName = "TestTemplate";
    private String target = "http://127.0.0.1:8080/iTextService/SamplePDF";
    
    public RequestITextService(){
        
    }
    
    private String getDataContent() throws Exception{
        BufferedReader dataBR = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = dataBR.readLine()) != null){
          buffer.append(line);
        } 
        return buffer.toString();
    }
    
    public byte[] request() throws Exception{
        URL url = new URL(target);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);  
  
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());  
        String parameter = "templateName="+templateName+"&dataXML=" + this.getDataContent();
        writer.write(parameter);  
        writer.flush();  
        writer.close();  
  
        InputStream in = conn.getInputStream();
        byte[] tmp = new byte[512];
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int bytesRead = in.read(tmp);
        while (bytesRead != -1) {
            out.write(tmp, 0, bytesRead);
            bytesRead = in.read(tmp);
        }
        return out.toByteArray();
    }
    
    public static void main(String[] args) throws Exception{
        FileOutputStream os = new FileOutputStream("D:\\sample.pdf");
        RequestITextService request = new RequestITextService();
        byte[] b = request.request();
        os.write(b);
        os.close();
    }
}
